# -*- encoding: utf-8 -*-

"""
@File:      tc_libtdb_libtdb_func_004.py.py
@Time:      2024/04/18 14:33:20
@Author:    chenchunhu
@Version:   1.0
@Contact:   wb-cch358909@alibaba-inc.com
@License:   Mulan PSL v2
@Modify:    chenchunhu
"""

from common.basetest import LocalTest

class Test(LocalTest):
    """
    See tc_libtdb_libtdb_func_004.py.yaml for details

    :avocado: tags=P2,noarch,local,fix
    """

    PARAM_DIC = {"pkg_name": "libtdb libtdb-devel gcc"}
    def setUp(self):
        super().setUp(self.PARAM_DIC)
        cmdline = '''cat >ltdb_test4.c<<"EOF"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <tdb.h>
#include <fcntl.h>

// 向数据库添加键值对的函数
static int add_kv(TDB_CONTEXT *tdb, const char *key_str, const char *value_str) {
    TDB_DATA key, value;
    key.dptr = (unsigned char *)key_str;
    key.dsize = strlen(key_str) + 1;
    value.dptr = (unsigned char *)value_str;
    value.dsize = strlen(value_str) + 1;

    // 尝试存储键值对
    return tdb_store(tdb, key, value, TDB_REPLACE);
}

int main() {
    TDB_CONTEXT *tdb;
    int ret;

    // 打开或创建数据库文件
    tdb = tdb_open("ltdb_test4.tdb", 0, TDB_DEFAULT | TDB_CLEAR_IF_FIRST, O_CREAT | O_RDWR, 0644);
    if (tdb == NULL) {
        fprintf(stderr, "打开或创建数据库失败\\n");
        return -1;
    }

    // 开启一个事务
    if (tdb_transaction_start(tdb) != 0) {
        fprintf(stderr, "开始事务失败\\n");
        tdb_close(tdb);
        return -1;
    }
    
    // 成功添加两个键值对
    if (add_kv(tdb, "key1", "value1") != 0 || add_kv(tdb, "key2", "value2") != 0) {
        fprintf(stderr, "添加键值对失败，准备回滚\\n");
        tdb_transaction_cancel(tdb);
        tdb_close(tdb);
        return -1;
    }
    
    // 模拟错误场景，添加第三个键值对失败
    if (add_kv(tdb, "key3", "intentionally-failed-value") != 0) {
        fprintf(stderr, "添加键值对时意图失败，触发回滚\\n");
        tdb_transaction_cancel(tdb);  // 回滚事务
        // 即使这里失败了，前两个添加的键值对也不会被保留
    } else {
        // 如果一切顺利，提交事务
        if (tdb_transaction_commit(tdb) != 0) {
            fprintf(stderr, "提交事务失败\\n");
            tdb_close(tdb);
            return -1;
        }
    }
    
    // 关闭数据库
    tdb_close(tdb);
    
    printf("所有操作执行完毕\\n");

    return 0;
}
EOF'''
        self.cmd(cmdline)


    def test(self):
        self.cmd("gcc -o ltdb_test4 ltdb_test4.c -ltdb")
        code, ltdb_result = self.cmd("./ltdb_test4")
        self.assertIn('所有操作执行完毕', ltdb_result)

    def tearDown(self):
        super().tearDown(self.PARAM_DIC)
        self.cmd("rm -rf ltdb_test4.c ltdb_test4 ltdb_test4.tdb")
